package cn.dapeng.ticket;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Ticket_Demo03 {

    private final CountDownLatch latch;

    private int tickets;

    private final Object monitor = new Object();

    public Ticket_Demo03(CountDownLatch latch, int tickets) {
        this.latch = latch;
        this.tickets = tickets;
    }

    public void sale() {
        SleepingUtil.sleep(1, TimeUnit.MILLISECONDS);
        synchronized (monitor) {
            System.out.println(Thread.currentThread().getName() + ":" + tickets--);
        }
        latch.countDown();
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();

        int threadCount = 10;
        CountDownLatch latch = new CountDownLatch(threadCount);
        Ticket_Demo03 demo03 = new Ticket_Demo03(latch, threadCount);

        for (int i = 0; i < threadCount; i++) {
            service.execute(new Thread(demo03::sale, "T" + i));
        }

        try {
            latch.await();
            System.out.println("Over");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
